import time
import re
import datetime
from lxml import etree
import requests
import json

from common.web.Base import Chrome
from autoTask.operaitonAid.pinduoduo.spiderFont import PddFont
from autoTask.operaitonAid.utils.request_data import requests_data
from common.logger.log import log_


class Task(Chrome):
    def __init__(self, queryList):
        super().__init__()
        self.min_date = datetime.datetime.strptime(queryList[0], "%Y-%m-%d")
        self.queryList = queryList
        self.dataList = self.init_List()

    def init_List(self):
        """初始化数据保存列表"""
        dataList = {}
        for query in self.queryList:
            dataList[query] = {
                'freeDelivery': 0,  # 免费送
                'supplementaryOrders': 0,  # 补单订单数量
                'brushOrdersAmount': 0.0,  # 刷单金额
            }
        return dataList

    def run(self):
        self.count_orders()
        self.get_pilot(self.queryList[0], self.queryList[-1])
        for query in self.queryList:
            log_.debug('====')
            row = self.dataList[query]
            row['supplementaryCommissionExpress'] = self.dataList[query]['supplementaryOrders'] * 0.3  # 补单佣金+快递
            info_effect = self.goods_effect(query)
            info_refund = self.get_refund(query)
            info_drainage = self.get_drainage(query)
            info_drainage_start = self.get_drainage_start_info(query)
            row.update(
                **info_effect,
                **info_refund,
                **info_drainage,
                **info_drainage_start
            )
            log_.debug(row)
            response = requests_data("post", uri="public/store/pdd/commit", params=row, req_title='拼多多店铺数据',
                                     req_is_log=False)
            if response.get('code') == 0:
                log_.info(f'{query}已保存')

    def goods_effect(self, this_date):
        """日期, 店铺名称, 商品访客数, 支付订单数, 支付转化率, 交易金额"""
        page = self.page
        url = f'https://mms.pinduoduo.com/sycm/goods_effect?dateFlag=5&day={this_date}'
        page.get(url)
        time.sleep(4)
        response = page.html
        font_handle = PddFont()
        font_handle.dbMap = {}
        font_handle.ttf_url = re.findall("(https://pfile.pddpic.com/webspider-sdk-api.*?ttf)", response, re.S)[0]
        font_handle.comparison()
        info = {
            'dataDate': this_date,
            'storeName': page.ele('x://div[@class="user-name-name"]/span[@class="user-name-text"]').text
        }
        arr = page.eles('x://div[@class="newCardInnerWrapper"]//span[@class="value __spider_font"]')
        info['visitor'] = font_handle.atob(arr[0].text)  # 商品访客数
        info['totalOrders'] = font_handle.atob(arr[3].text)  # 支付订单数
        info['conversionRate'] = font_handle.atob(arr[4].text)  # 支付转化率
        info['totalStoreSales'] = font_handle.atob(arr[5].text)  # 交易金额
        log_.debug(f'effect: {info}')
        return info

    def get_refund(self, this_date):
        """退款金额"""
        page = self.page
        url = f'https://mms.pinduoduo.com/sycm/goods_quality/detail?dateFlag=5&day={this_date}'
        page.get(url)
        refund = page.ele('x://div[@class="newCardInnerWrapper"]/div[8]/div/p/span').text
        log_.debug(f'refundAmount: {str_to_float(refund)}')
        return {
            'refundAmount': str_to_float(refund)
        }

    def get_drainage(self, this_date):
        """平台引流页面调度"""
        urls = [
            ['goods/report/odin/overView', 'websitePromotion', 'websitePromotionDeal'],
            ['goods/report/search/overView', 'duoduoSearch', 'searchDeal'],
            ['goods/report/scene/overView', 'duoduoScene', 'sceneDeal'],
        ]
        info_drainage = {}
        for row in urls:
            info_drainage.update(self.get_drainage_info(row, this_date))
        return info_drainage

    def get_drainage_info(self, row, this_date):
        """引流页面信息"""
        url = f'https://yingxiao.pinduoduo.com/{row[0]}?beginDate={this_date}&endDate={this_date}'
        page = self.page
        page.get(url)
        box = page.ele('x://div[@class="Header_line__ke1jK"]')
        box.ele('tx:表格', timeout=3).click()
        time.sleep(2)
        hf = page.ele('x://tfoot[@class="anq-table-summary"]//td[@class="anq-table-cell"][2]/div/div[1]').text
        jy = page.ele('x://tfoot[@class="anq-table-summary"]//td[@class="anq-table-cell"][3]/div/div[1]').text
        log_.debug(f'{row[1]}: {str_to_float(hf)}, {row[2]}: {str_to_float(jy)}')
        return {
            row[1]: str_to_float(hf),
            row[2]: str_to_float(jy),
        }

    def get_drainage_start_info(self, this_date):
        """明星引流 页面不一致 分开操作"""
        url = f'https://yingxiao.pinduoduo.com/starmall/report/overView?beginDate={this_date}&endDate={this_date}'
        page = self.page
        page.get(url)
        box = page.ele('x://div[@class="Header_line__ke1jK"]')
        box.ele('tx:表格', timeout=3).click()
        time.sleep(2)
        hf = page.ele('x://tfoot[@class="anq-table-summary"]//td[@class="anq-table-cell"][1]/div/div[1]').text
        jy = page.ele('x://tfoot[@class="anq-table-summary"]//td[@class="anq-table-cell"][2]/div/div[1]').text
        log_.debug(f'starStorePromotion: {str_to_float(hf)}, starStoreDeal: {str_to_float(jy)}')
        return {
            'starStorePromotion': str_to_float(hf),
            'starStoreDeal': str_to_float(jy),
        }

    def count_orders(self):
        """订单遍历统计"""
        self.orders_option()
        self.find_orders()

    def find_orders(self):
        """查找订单"""
        page = self.page
        time.sleep(2)
        response = etree.HTML(page.html)
        orders = response.xpath('//tbody[@data-testid="beast-core-table-middle-tbody"]')
        for row in orders:
            this_date = row.xpath('tr[1]/td/div/div/div/div[2]/span/text()')[0]
            this_date = self.order_date_change(this_date)
            this_state = row.xpath('tr[2]/td/div[@class="orderState"]/text()')[0]
            this_tag = row.xpath('tr[2]/td[8]/div/div/div[2]/div/div/div/div[2]/text()')
            this_collect = str_to_float(row.xpath('tr[2]/td[5]/div/span/span/text()')[0])
            # 日期判断
            date_state = self.order_check_date(this_date)
            if date_state is False:  # 目标日期大于订单日期 return退出搜索
                return
            if this_date not in self.queryList:
                continue
            # 状态判断
            if this_state not in ['已发货，待签收', '已签收', '待发货', '未发货，退款成功', '已发货，退款成功']:
                continue
            # 备注判断
            if this_tag:
                if this_tag[0] == '绿色':
                    self.dataList[this_date]['supplementaryOrders'] += 1
                    self.dataList[this_date]['brushOrdersAmount'] += this_collect
            if this_collect == 0.0:
                self.dataList[this_date]['freeDelivery'] += 1
        self.next_page()

    def orders_option(self):
        """设置遍历订单条件"""
        url = 'https://mms.pinduoduo.com/orders/list'
        page = self.page
        page.get(url)
        self.close_section()
        page.ele('x://div[@class="_list-quick-search"]/div/li[1]', timeout=3).click()
        # 备注筛选
        time.sleep(1)
        page.scroll.to_bottom()
        num_input = page.ele('x://li[@class="PGT_sizeChanger_5-89-1"]//input', timeout=3)
        if not num_input:
            return
        if num_input.attrs['value'] != 50:
            num_input.click()
            list_box = page.ele('x://ul[@role="listbox"]')
            list_box.ele('tx:50').click()

    # 关闭浮动窗口
    def close_section(self):
        page = self.page
        overdue = page.ele('x://div[@data-testid="beast-core-modal-inner"]', timeout=1)
        if overdue:
            overdue.ele('tx:暂不处理').click()
        section_show = page.ele('x://section[@class="NewMsgBox_important-wrapper__2ZwS8"]//i', timeout=1)
        if section_show:
            section_show.click()

    @staticmethod
    def order_date_change(order_date):
        """目标日期与成交时间作对比"""
        order_date = re.findall('成交时间：(.*?) ', order_date)[0]
        # order_date = datetime.datetime.strptime(order_date, "%Y-%m-%d")
        return order_date

    def order_check_date(self, order_date):
        """目标日期与成交时间作对比"""
        order_date = datetime.datetime.strptime(order_date, "%Y-%m-%d")
        if self.min_date > order_date:
            return False
        else:
            return True

    def next_page(self):
        """点击下一页"""
        page = self.page
        self.close_section()
        page.scroll.to_bottom()
        nextCheck = page.ele('x://li[@data-testid="beast-core-pagination-next"]')
        if nextCheck:
            log_.debug('next page')
            try:
                page('x://li[@data-testid="beast-core-pagination-next"]', timeout=3).click()
                self.find_orders()
            except:
                pass
        else:
            return False

    def headers(self):
        """获取请求头"""
        cookies = ''
        for key, value in self.page.cookies.items():
            if key in ['JSESSIONID', 'PASS_ID']:
                cookies += f"{key}={value};"
        return {
            'Host': 'mms.pinduoduo.com',
            'content-type': 'application/json',
            'Accept-Encoding': 'gzip, deflate, br',
            'Cookie': cookies
        }

    def get_pilot(self, beginDate, endDate):
        """领航员数据"""
        if beginDate == endDate:
            date_obj = datetime.datetime.strptime(endDate, "%Y-%m-%d")
            new_date = date_obj + datetime.timedelta(days=1)
            endDate = new_date.strftime("%Y-%m-%d")
        url = 'https://mms.pinduoduo.com/sydney/api/mallNavigator/queryUpgradeMallNavigatorList'
        data = {
            "beginDate": beginDate,
            "endDate": endDate
        }
        response = requests.post(url, headers=self.headers(), data=json.dumps(data))
        response_json = response.json()
        for row in response_json['result']:
            if row['mallId'] is None:
                continue
            this_date = row['pt']
            dic = {
                'helpRate': round(row['ptHelpRate1m'] * 100, 2),
                'comprehensiveScoreIndustryRanking': int(row['scoreRk']),
            }
            if this_date in self.dataList:
                self.dataList[this_date].update(dic)


def str_to_float(val):
    val = re.sub('%', '', val)
    val = re.sub(',', '', val)
    return float(val)


def str_to_int(val):
    val = re.sub('%', '', val)
    val = re.sub(',', '', val)
    return int(val)


if __name__ == '__main__':
    Task(['2023-10-29']).run()
    # Task(['2023-10-10']).orders_option()
